import router, { asyncRoutes, constantRoutes, resetRouter } from '@/router';
import { AccountInfoService } from '@/services/security/AccountInfo';

const hasAuthority = (route, info) => {
	if (route.meta && route.meta.authority) {
		return AccountInfoService.isAllowed(
			route.meta.authority.roles,
			route.meta.authority.accesses,
			info
		);
	} else {
		return true;
	}
};

export const filterAsyncRoutes = (routes, info) => {
	const res = [];
	routes.forEach(route => {
		const tmp = { ...route };
		if (hasAuthority(tmp, info)) {
			if (tmp.children) {
				tmp.children = filterAsyncRoutes(tmp.children, info);
			}
			res.push(tmp);
		}
	});

	return res;
};

const state = {
	allRoutes: [],
	addRoutes: [],
	time: null
};

const mutations = {
	ADD_ROUTES: (state, addRoutes) => {
		state.addRoutes = addRoutes;
		state.allRoutes = constantRoutes.slice(0, -1).concat(addRoutes);
	},
	APPLY_ROUTES: (state, addRoutes) => {
		router.addRoutes(addRoutes);
	},
	SET_TIME: (state, time) => {
		state.time = time;
	}
};

const actions = {
	generateRoutes({ commit }, info) {
		return new Promise(resolve => {
			// console.log('async', asyncRoutes);
			const addRoutes = filterAsyncRoutes(asyncRoutes, info);
			commit('ADD_ROUTES', addRoutes);
			resetRouter();
			commit('APPLY_ROUTES', addRoutes);
			commit('SET_TIME', info.time);
			resolve(addRoutes);
		});
	}
};

export default {
	namespaced: true,
	state,
	mutations,
	actions
};
